package org.rslai.tcedit.util;

import java.io.File;
import java.io.IOException;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.EncodedResource;
import java.io.FileOutputStream;

public class XmlUtil {

	/**
	 * 读取XML配置文件
	 * @param res Resource
	 * @return 返回打开的xml文档
	 * @throws DocumentException
	 * @throws IOException
	 */
	public Document loadFromXML(Resource res) throws DocumentException, IOException {
		EncodedResource encRes = new EncodedResource(res, "UTF-8");
		SAXReader reader = new SAXReader();
		return reader.read(encRes.getReader());
	}

	/**
	 * 写XML配置文件
	 * @param doc Document对象
	 * @param fileName XML文件名
	 * @throws IOException
	 */
	public void writerXML(Document doc, String fileName) throws IOException {
		OutputFormat format = OutputFormat.createPrettyPrint();
		format.setEncoding("UTF-8"); // 设置XML文件的编码格式，可设置为GBK或UTF-8

		File file = new File(fileName);
		XMLWriter writer = null;

		/**
		 * 如果上面设置为GBK，则应当用FileWriter，否则还是会出现乱码问题
		 * 如果上面设置为UTF-8，则应当用FileOutputStream，否则还是会出现乱码问题
		 */
		// writer = new XMLWriter(new FileWriter(file), format);
		FileOutputStream fos = new FileOutputStream(file);

		writer = new XMLWriter(fos, format);
		writer.write(doc);
		writer.close();
	}

}
